package top.hkyzf.study.leetcode.array;

import org.junit.Test;

import java.util.Arrays;

/**
 * @author 朱峰
 * @date 2022-1-21 10:38
 */
public class 两数之和II_输入有序数组_167 {
    public int[] twoSum(int[] numbers, int target) {
        int x = 0;
        int y = 0;
        if (numbers.length < 2) {
            return null;
        }
        if(numbers.length == 2) {
            if (numbers[0] + numbers[1] == target) {
                return new int[]{1, 2};
            }
        }
        if (numbers[0] > target) {
            return null;
        }
        for (int i = 0; i < numbers.length-1; i++) {
            x = i+1;
            int another = target - numbers[i];
            for (int j = i+1; j < numbers.length; j++) {
                y = j+1;
                if (numbers[j] > another) {
                    break;
                }
                if (numbers[j] == another) {
                    return new int[]{x, y};
                }
            }
        }
        return null;
    }

    public int[] twoSum1(int[] numbers, int target) {
        int left = 0;
        int right = numbers.length-1;
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            if (sum == target) {
                return new int[]{left+1, right+1};
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return null;
    }

    @Test
    public void testTwoSum () {
        int[] numbers = {1,2,3,4,4,9,56,90};
        int target = 8;
        int[] ints = twoSum1(numbers, target);
        System.out.println(Arrays.toString(ints));
    }
}
